package com.cheng.example.atguigu.view2.client43;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 锁绑定多个条件Condition测试
 */
class ShareResouse {
    private int number = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void condition1() {
        lock.lock();
        try {
            //1、判断
            while (number != 1) {
                //等待，不能生产
                condition1.await();
            }
            //2、干活
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            number = 2;
            condition2.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void condition2() {
        lock.lock();
        try {
            //1、判断
            while (number != 2) {
                //等待，不能生产
                condition2.await();
            }
            //2、干活
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            number = 3;
            condition3.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void condition3() {
        lock.lock();
        try {
            //1、判断
            while (number != 3) {
                //等待，不能生产
                condition3.await();
            }
            //2、干活
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            number = 1;
            condition1.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class OrderCondition {
    public static void main(String[] args) {
        ShareResouse shareResouse = new ShareResouse();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResouse.condition1();
            }
        }, "AAA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResouse.condition2();
            }
        }, "BBB").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResouse.condition3();
            }
        }, "CCC").start();
    }

}
